package com.example.dishit.view.recommendation;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.example.dishit.R;
import com.example.dishit.controller.recommendation.IRecommendationController;
import com.example.dishit.controller.recommendation.RecommendationController;
import com.example.dishit.model.dish.DishData;
import com.example.dishit.view.alert.AlertView;

public class RecommendationActivity extends Activity implements IRecommendationView {
    private IRecommendationController controller;
    private static final String EMBED_MAP_URL = "&output=embed";
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recommendation);
        
        final DishData restaurant = (DishData)(getIntent().getSerializableExtra(DishData.DISH_DATA_KEY));
        
        // See if this needs to reset the "number of unopened alerts" counter. 
        final boolean resetNumUnopened = getIntent().getBooleanExtra(AlertView.RESET_NUM_UNOPENED_KEY, false);
        if(resetNumUnopened) AlertView.resetCounter();
        
        // Create a controller. Pass in this view.
         controller = new RecommendationController(this, restaurant);
        
        // Draw this Activity using the recommendation.
        draw(restaurant);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_recommendation, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigationButton:
                controller.openMap();
                return true;
            case R.id.phoneNumButton:
                controller.dialRestaurant();
                return true;
            case R.id.websiteButton:
                controller.openWebsite();
                return true;
            case R.id.tryAgainButton:
                controller.tryAgain();
                return true;
            case R.id.doneButton:
                controller.close();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    private final Executor imageRetrievalThread = Executors.newSingleThreadExecutor(); 
    
    public void draw(final DishData restaurant) {
        // TITLE
        setTitle(restaurant.getRestaurantName());
        
        // PRICE RANGE
        final TextView priceView = (TextView)findViewById(R.id.priceValue);
        final String minStr = (restaurant.getPriceMin() != null) ? restaurant.getPriceMin().toString()
                                                                 : "---";
        final String maxStr = (restaurant.getPriceMax() != null) ? restaurant.getPriceMax().toString()
                                                                 : "---";
        priceView.setText("$" + minStr + " - " + maxStr);
        
        // IMAGE GALLERY
        final List<String> imageUrls = restaurant.getImageUrls();
        if(imageUrls != null && !imageUrls.isEmpty()) {
            final Activity thisContext = this;
            imageRetrievalThread.execute(new Runnable() {
                public void run() {
                    final ViewGroup imgGallery = (ViewGroup)findViewById(R.id.imgGallery);
                    for(final String imageUrl : imageUrls) {
                        // Create new ImageView.
                        final ImageView imageView = new ImageView(thisContext);
                        imageView.setImageDrawable(loadImageFromURL(imageUrl));
                        imageView.setMinimumWidth(100);
                        imageView.setMinimumHeight(100);
                        imageView.setBackgroundColor(Color.BLACK);
                        imageView.setPadding(10, 10, 10, 10);
                        
                        // Add it to the gallery.
                        thisContext.runOnUiThread(new Runnable() {
                            public void run() {
                                imgGallery.addView(imageView);
                            }
                        });
                    }
                }
            });
        }
        
        // KEYWORDS
        final TextView keywordsView = (TextView)findViewById(R.id.keywordsValue);
        final List<String> keywords = restaurant.getKeywords();
        if(keywords != null && !keywords.isEmpty()) {
            keywordsView.setText(keywords.toString());
        } else {
            keywordsView.setText("---");
        }
        
        // CHOSEN BECAUSE...
        final TextView reasonView = (TextView)findViewById(R.id.reasonValue);
        final List<String> reasons = restaurant.getReasons();
        if(reasons != null && !reasons.isEmpty()) {
            reasonView.setText(reasons.toString());
        } else {
            reasonView.setText("---");
        }
        
        // RATING
        final RatingBar ratingBar = (RatingBar)findViewById(R.id.recommendation_rating_bar);
        final Float rating = restaurant.getRating();
        final float ratingVal = (rating != null) ? rating : 0f;
        ratingBar.setRating(ratingVal);
        
        // COMMENTS
        final TextView commentsView = (TextView)findViewById(R.id.commentsTextView);
        final List<String> comments = restaurant.getComments();
        if(comments != null && !comments.isEmpty()) {
            final StringBuilder commentsText = new StringBuilder();
            for(final String comment : restaurant.getComments()) {
                if(commentsText.length() > 0) commentsText.append("\n\n");
                
                commentsText.append(comment);
            }
            commentsView.setText(commentsText.toString());
        } else {
            commentsView.setText("");
        }
        
        // MAP CAPTION
        final StringBuilder mapTextSb = new StringBuilder();
        
        final String streetAddr = restaurant.getStreetAddress();
        if(streetAddr != null && !streetAddr.isEmpty())
            mapTextSb.append(streetAddr).append(", ");
        
        final String city = restaurant.getCity();
        if(city != null && !city.isEmpty())
            mapTextSb.append(city).append(", ");
        
        final String state = restaurant.getState();
        if(state != null && !state.isEmpty())
            mapTextSb.append(state).append(" ");
        
        final String zipcode = restaurant.getZipcode();
        if(zipcode != null && !zipcode.isEmpty())
            mapTextSb.append(zipcode).append("\n");
        
        final String phoneNumDigits = restaurant.getPhoneNumberDigits();
        if(phoneNumDigits != null && !phoneNumDigits.isEmpty())
            mapTextSb.append(toPhoneNumString(phoneNumDigits)).append("\n");
        
        final String websiteUrl = restaurant.getWebsiteUrl();
        if(websiteUrl != null && !websiteUrl.isEmpty())
            mapTextSb.append(websiteUrl);
        
        final TextView mapTextView = (TextView)findViewById(R.id.mapText);
        final String mapText = (mapTextSb.length() > 0) ? mapTextSb.toString() : "";
        mapTextView.setText(mapText);
        
        // MAP
        final WebView mapWebView = (WebView) findViewById(R.id.mapWebView);
        final String mapUrl = restaurant.getMapUrl();
        if(mapUrl != null && !mapUrl.isEmpty()) {
            final Activity thisActivity = this;
            mapWebView.getSettings().setJavaScriptEnabled(true);
            mapWebView.getSettings().setBuiltInZoomControls(true);
            mapWebView.getSettings().setSupportZoom(true);
            mapWebView.setWebChromeClient(new WebChromeClient() {
                public void onProgressChanged(WebView view, int progress) {
                    // Activities and WebViews measure progress with different scales.
                    // The progress meter will automatically disappear when we reach 100%
                    ((Activity) thisActivity).setProgress(progress * 1000);
                }
            });
            //mapWebView.setWebViewClient(new WebViewClient());
            
            // Load the map.
            mapWebView.loadUrl(mapUrl + EMBED_MAP_URL);
            //mapWebView.loadData("<html><body>Here is a <b><i>map</b></i> to the restaurant.</body></html>", "text/html", null);
        } else {
            mapWebView.setVisibility(View.INVISIBLE);
        }
    }
    
    private static String toPhoneNumString(final String phoneNumberDigits) {
        if(phoneNumberDigits == null || phoneNumberDigits.isEmpty()) {
            return "No phone number provided.";
        } else if(phoneNumberDigits.length() == 7) {
            return new StringBuilder()
                .append(phoneNumberDigits.subSequence(3, 6))
                .append("-")
                .append(phoneNumberDigits.subSequence(6, 10))
                .toString();
        } else if(phoneNumberDigits.length() == 10) {
            return new StringBuilder("(")
                .append(phoneNumberDigits.subSequence(0, 3))
                .append(") ")
                .append(phoneNumberDigits.subSequence(3, 6))
                .append("-")
                .append(phoneNumberDigits.subSequence(6, 10))
                .toString();
        } else {
            return phoneNumberDigits;
        }
    }
    
    private Drawable loadImageFromURL(String url) {
        Drawable drawable = null;
        try {
            final InputStream is = (InputStream) new URL(url).getContent();
            drawable = Drawable.createFromStream(is, "srcname");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return drawable;
        
        // return getResources().getDrawable(R.drawable.cutters);
    }
}
